const chrome = window.chrome
const storage = chrome.storage;
// 监听浏览器标签页的创建和关闭事件
chrome.tabs.onCreated.addListener(updateTabList);
chrome.tabs.onRemoved.addListener(updateTabList);
chrome.tabs.onActivated.addListener(updateTabList);
chrome.tabs.onReplaced.addListener(updateTabList);
chrome.tabs.onUpdated.addListener(updateTabList);
function updateTabList() {
  chrome.tabs.query({ currentWindow: true }, function (tabs) {
    for (let i = 0; i < tabs.length; i++) {
      if (tabs[i].active) {
        let tableid = tabs[i].id
        chrome.tabs.get(tableid, function (tab) {
          // 获取当前活动标签页的详细信息
          let str = 'ruten.com.tw/'
          let url = tab.url == '' ? tab.pendingUrl : tab.url
          if (url.includes(str)) {
            chrome.action.setPopup({ popup: './popup.html' });
          } else {
            chrome.action.setPopup({ popup: '' });
          }
        });
      }

    }
  })

}


chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  // if (request.data.action === 'rescookiedataLutinrobot') {
  //   sendResponse({
  //     message: "success"
  //   });
  //   if (request.data.robotputinnum == 0) {
  //     chrome.tabs.query({ currentWindow: true, active: true }, (tabs) => {
  //       saveData(tabs[0].id, 'robotputintabsid')
  //     })
  //   }

  //   lutinrobotPutin(request.data)
  // }
  if (request.data.action === 'getrelationData') {
    sendResponse({
      message: "success"
    });
    chrome.tabs.query({ currentWindow: true, active: true }, (tabs) => {
      saveData(tabs[0].id, 'relationtabsid')
    })

    getrelationData(request.data)
  } else if (request.data.action === 'getcloserelation') {
    sendResponse({
      message: "success"
    });
    chrome.tabs.query({ currentWindow: true, active: true }, (tabs) => {
      saveData(tabs[0].id, 'relationtabsid')
    })

    getcloserelation(request.data)
  }
});

function getrelationData(data) {
  fetch(`https://rapi.ruten.com.tw/api/rtb/v1/index.php/${data.usernick}/order_list?duration=${data.time}&column=r_status&sort=asc&status=progress&ta_status=all&s_date=${data.relationTmie.field1}&e_date=${data.relationTmie.field2}&q=`, {
    method: 'get',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      'Referer': `https://promote.ruten.com.tw/rtb/order_list.php`,
      'Origin': 'https://promote.ruten.com.tw'
    }
  }).then(response => response.json()).then(res => {
    console.log(res);
    if (res.status == "success") {
      sendMessageToTab({ action: 'resgetrelationData', data: res });
    }
  }).catch(error => {
    console.log(error);
  });
}

function getcloserelation(data) {
  // let formData = new URLSearchParams();
  formData.append('extend_status', false);

  fetch(`https://rapi.ruten.com.tw/api/rtb/v1/index.php/${data.usernick}/extend/${data.gno}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      'Referer': `https://promote.ruten.com.tw/rtb/kword_list.php?g_no=${data.gno}`,
      'Origin': 'https://promote.ruten.com.tw'
    },
    body: formData
  }).then(response => response.json()).then(res => {
    console.log(res);
    // console.log(code);
    if (res.status == "success") {
      sendMessageToTab({ action: 'resgetcloserelationno' });
    } else {
      sendMessageToTab({ action: 'resgetcloserelationno'});
    }
  }).catch(error => {
    console.log(error);
    sendMessageToTab({ action: 'resgetcloserelationno'});
  });
}



// 保存数据到chrome.storage
function saveData(data, key) {
  const obj = {};
  obj[key] = data;
  storage.local.set(obj, function () {
    // //console.log('Data saved successfully.');
  });
}


// 读取chrome.storage中的数据
function loadData(key, callback) {
  chrome.storage.local.get([key], function (result) {
    const data = result[key];
    callback(data);
  });
}



function sendMessageToTab(message) {
  loadData('relationtabsid', function (tabsid) {
    // console.log(tabsid);
    chrome.tabs.sendMessage(tabsid, message);
  })

}


